#!/usr/bin/perl -w
use strict;
use Getopt::Long;

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

my $usage = <<'USAGE';

USAGE:

    re_replace_filter.pl
                --from_regex "([^\t]+)\t"
                --to_regex "\$1"
				--keep_non_matching_lines
				[--help]
	
	Iterates through files and filters each line according to the supplied
		regular expression
	Equivalent to running over each line
		print if s/from_regex/to_regex/;
		
	
	Prints to STDOUT
USAGE


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory
my $to_regex;
my $from_regex;
my $keep_non_matching_lines;

# optional parameters
my $help;
GetOptions(
			'to_regex=s'		=> \$to_regex,
			'from_regex=s'		=> \$from_regex,
			'keep_non_matching_lines'	=> \$keep_non_matching_lines,
			'help'				=> \$help);

die $usage if ($help);
die $usage unless ($from_regex && $to_regex);


my $cmd = <<"CMD";
	for (<>)
	{
		if (s/$from_regex/{\"$to_regex\"}/e)
		{
			print;
		}
	}
CMD

my $cmd_keep = <<"CMD";
	for (<>)
	{
		s/$from_regex/{\"$to_regex\"}/e;
		print;
	}
CMD

if ($keep_non_matching_lines)
{
	eval $cmd_keep;
}
else
{
	eval $cmd ;
}
#for (<>) { s/([^\t]+)\t([^\t]+)/{"$1\t"}/e; print; }
